package com.wx.cloud.zull.config;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.wx.cloud.zull.util.JwtTokenUtil;
import io.jsonwebtoken.ExpiredJwtException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Set;

@Component
public class LogFilter extends ZuulFilter {
    @Value("#{'${pahtList}'.split(',')}")
    private List<String> pahtList;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    public String filterType() {
        return "pre";
    }

    public int filterOrder() {
        return 0;
    }

    public boolean shouldFilter() {
        return true;

    }

    public Object run() throws ZuulException {
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletResponse response = requestContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        HttpServletRequest request = requestContext.getRequest();
//        如果包含login登录就直接放行
        String u = request.getRequestURI();
        String uri = u.replaceAll("/", ":");
        boolean p = pahtList.stream().anyMatch(paht -> StringUtils.contains(uri,paht));
        //contains就是uri对象里面是否包含paht字符串,有就直接返回
        if (p){
            return null;
        }
        String authorization = request.getHeader("Authorization");
        String token = StringUtils.substring(authorization, "bearer".length()).trim();

        Set<String> authority= null;
        try {
            authority = jwtTokenUtil.getAuthorityFromToken(token);
        } catch (Exception e) {
            //验证token是否已过期
            if (e instanceof ExpiredJwtException){
                requestContext.setResponseBody(JSON.toJSONString("token 过期"));
                return null;
            }
            e.printStackTrace();
        }

//        //验证是否有相应权限
//        String ur=uri.substring(1);
//        boolean b = authority.stream().anyMatch(auth -> StringUtils.equals(auth,ur));
//        if (!b){
//            requestContext.setResponseBody(JSON.toJSONString("你没有权限"));
//            return null;
//        }
        return null;
    }
}